import {fetch} from '@/utils/fetch'
import {document, page, user, task, group} from '../fragment'

export const create = async ({ id = 0, name, type = 'page', data = null, layout = null, meta = null, endAt = null }) => {
  let res = await fetch({
    query: `mutation ($id: Int, $name: String!, $type: DocType!, $data: JSON, $layout: JSON, $meta: JSON, $endAt: String) {
      createDocument (input: {
        id: $id,
        name: $name,
        type: $type,
        data: $data,
        layout: $layout,
        meta: $meta,
        endAt: $endAt
      }) {
        ${document}
        user {
          ${user}
        }
      }
    }`,
    variables: {
      id,
      name,
      type,
      data,
      layout,
      meta,
      endAt
    }
  })
  return res.data.createDocument
}

export const publish = async ({
  documentId, groupIds, endAt = '', prePublishAt = ''
}) => {
  let res = await fetch({
    query: `mutation ($documentId: Int!, $groupIds: [Int!]!, $endAt: String, $prePublishAt: String) {
      documentPublish (
        documentId: $documentId,
        groupIds: $groupIds,
        endAt: $endAt,
        prePublishAt: $prePublishAt
      ) {
        ${task}
        document {
          ${document}
        }
        group {
          ${group}
        }
      }
    }`,
    variables: {
      documentId,
      groupIds,
      endAt,
      prePublishAt
    }
  })
  return res.data.documentPublish
}

export const getById = async (documentId) => {
  let res = await fetch({
    query: `{
      getDocumentById (id: ${documentId}) {
        ${document},
        user {
          ${user}
        }
      }
    }`,
    cache: false
  })
  return res.data.getDocumentById
}

export const getByPage = async ({pageIndex = 0, pageSize = 20, cache = true}) => {
  let res = await fetch({
    query: `{
      documents (pageIndex: ${pageIndex}, pageSize: ${pageSize}) {
        ${page}
        rows {
          ${document}
          answerers {
            ${user}
          }
        }
      }
    }`,
    cache
  })
  return res.data.documents
}

export const getUnpublishes = async () => {
  let res = await fetch({
    query: `{
      documentUnpublishes {
        ${document}
      }
    }`,
  })
  return res.data.documentUnpublishes
}
